package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.print.DocFlavor;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author guomo
 * @date 2025-10-10
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 保存入住申请。
     *
     * @param dto 入住申请数据传输对象
     * @return 返回1表示成功，返回0表示失败
     * @throws BaseException 如果老人已经入住或者床位信息错误则抛出异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveApply(CheckInApplyDto dto) {
        if (dto == null) {
            return 0;
        }
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        //校验老人是否入住
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        queryWrapper.eq(Elder::getStatus, 4);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (elder != null) {
            throw new BaseException("该老人已经入住");
        }
        //更新床位状态
        Long bedId = checkInConfigDto.getBedId();
        Bed bed = bedMapper.selectBedById(bedId);
        if (bed == null) {
            // 如果查询到的床位信息为空，则抛出异常，提示用户输入正确的床号
            throw new BaseException("请输入正确的床号");
        }
        bed.setBedStatus(1);
        bedMapper.updateById(bed);


        //新增或更新老人
        elder = saveOrUpdateElder(checkInElderDto, checkInConfigDto, bed);

        //新增合同信息
        saveContract(elder, checkInConfigDto, checkInContractDto);

        //新增入住信息
        CheckIn checkIn = saveCheckin(checkInConfigDto, elder, elderFamilyDtoList);

        //新增入住配置
        saveCheckinConfig(checkInConfigDto,  elderFamilyDtoList,checkIn);

        return 1;
    }

    /**
     * 查询入住详情信息。
     * @param id 入住记录的ID。
     * @return 返回一个包含入住老人详情的CheckInDetailVo对象。
     * @throws BaseException 如果ID为空，则抛出此异常。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CheckInDetailVo selectCheckInDetailVo(Long id) {
        if(id==null){
            throw new BaseException("ID不能为空");
        }
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectById(elderId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        checkInElderVo.setName(elder.getName());
        checkInElderVo.setIdCardNo(elder.getIdCardNo());
        checkInElderVo.setBirthday(elder.getBirthday());
        checkInElderVo.setSex(elder.getSex());
        checkInElderVo.setPhone(elder.getPhone());
        checkInElderVo.setAddress(elder.getAddress());
        checkInElderVo.setImage(elder.getImage());
        checkInElderVo.setIdCardNationalEmblemImg(elder.getIdCardNationalEmblemImg());
        checkInElderVo.setIdCardPortraitImg(elder.getIdCardPortraitImg());
        int age = DateUtil.ageOfNow(elder.getBirthday());
        checkInElderVo.setAge(age);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //家属信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> list = JSONUtil.toList(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(list);

        //入住配置信息
        LambdaQueryWrapper<CheckInConfig> configLambdaQueryWrapper = new LambdaQueryWrapper<>();
        configLambdaQueryWrapper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(configLambdaQueryWrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setId(checkIn.getId());
        checkInConfigVo.setCheckInId(checkIn.getId());
        checkInConfigVo.setNursingLevelId(checkInConfig.getNursingLevelId());
        checkInConfigVo.setNursingLevelName(checkIn.getNursingLevelName());
        checkInConfigVo.setFeeStartDate(checkInConfig.getFeeStartDate());
        checkInConfigVo.setFeeEndDate(checkInConfig.getFeeEndDate());
        checkInConfigVo.setDeposit(checkInConfig.getDeposit());
        checkInConfigVo.setNursingFee(checkInConfig.getNursingFee());
        checkInConfigVo.setBedFee(checkInConfig.getBedFee());
        checkInConfigVo.setInsurancePayment(checkInConfig.getInsurancePayment());
        checkInConfigVo.setGovernmentSubsidy(checkInConfig.getGovernmentSubsidy());
        checkInConfigVo.setOtherFees(checkInConfig.getOtherFees());
        checkInConfigVo.setSortOrder(checkInConfig.getSortOrder());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //入住合同
        LambdaQueryWrapper<Contract> contractLambdaQueryWrapper = new LambdaQueryWrapper<>();
        contractLambdaQueryWrapper.eq(Contract::getElderId,elderId);
        Contract contract = contractMapper.selectOne(contractLambdaQueryWrapper);
        checkInDetailVo.setContract(contract);


        return checkInDetailVo;
    }

    /**
     * 保存入住配置信息。
     * @param checkInConfigDto 入住配置数据传输对象，包含入住配置的详细信息。
     * @param elderFamilyDtoList 长者家庭数据传输对象列表，包含长者及其家庭相关信息。
     * @param checkIn 入住实体对象，用于获取入住ID。
     */
    private void saveCheckinConfig(CheckInConfigDto checkInConfigDto,  List<ElderFamilyDto> elderFamilyDtoList,CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setNursingLevelId(checkInConfigDto.getNursingLevelId());
        checkInConfig.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkInConfig.setFeeStartDate(checkInConfigDto.getFeeStartDate());
        checkInConfig.setFeeEndDate(checkInConfigDto.getFeeEndDate());
        checkInConfig.setDeposit(checkInConfigDto.getDeposit());
        checkInConfig.setNursingFee(checkInConfigDto.getNursingFee());
        checkInConfig.setBedFee(checkInConfigDto.getBedFee());
        checkInConfig.setInsurancePayment(checkInConfigDto.getInsurancePayment());
        checkInConfig.setGovernmentSubsidy(checkInConfigDto.getGovernmentSubsidy());
        checkInConfig.setOtherFees(checkInConfigDto.getOtherFees());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 保存入住信息。
     * @param checkInConfigDto 入住配置数据传输对象
     * @param elder 老人实体信息
     * @param elderFamilyDtoList 老人家属数据传输对象列表
     * @return 返回保存后的入住信息
     */
    private CheckIn saveCheckin(CheckInConfigDto checkInConfigDto, Elder elder, List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(elder.getStatus());
        String jsonStr = JSONUtil.toJsonStr(elderFamilyDtoList);
        checkIn.setRemark(jsonStr);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 保存合同信息。
     * @param elder 老人信息对象，包含老人的基本信息。
     * @param checkInConfigDto 入住配置数据传输对象，包含入住相关的配置信息。
     * @param checkInContractDto 入住合同数据传输对象，包含合同的具体信息。
     */
    private void saveContract(Elder elder, CheckInConfigDto checkInConfigDto, CheckInContractDto checkInContractDto) {
        Contract contract = new Contract();
        contract.setElderId(elder.getId());
        contract.setContractName(checkInContractDto.getContractName());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setAgreementPath(checkInContractDto.getAgreementPath());
        contract.setThirdPartyPhone(checkInContractDto.getThirdPartyPhone());
        contract.setThirdPartyName(checkInContractDto.getThirdPartyName());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(elder.getStatus());
        contract.setSignDate(checkInContractDto.getSignDate());
        contractMapper.insert(contract);
    }

    /**
     * 保存或更新老人信息。
     * 根据提供的身份证号码查询老人信息，如果不存在则创建新记录，如果存在则更新记录。
     *
     * @param checkInElderDto 老人入住信息传输对象
     * @param checkInConfigDto 入住配置信息传输对象
     * @param bed 床位信息
     * @return 返回更新后的老人信息
     */
    private Elder saveOrUpdateElder(CheckInElderDto checkInElderDto, CheckInConfigDto checkInConfigDto, Bed bed) {
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (elder == null) {
            elder = new Elder();
            BeanUtils.copyProperties(checkInElderDto, elder);
            elder.setStatus(4);
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.insert(elder);
        } else {
            BeanUtils.copyProperties(checkInElderDto, elder);
            elder.setStatus(4);
            elder.setBedNumber(checkInConfigDto.getCode());
            elder.setBedId(checkInConfigDto.getRoomId());
            elderMapper.updateById(elder);
        }
        return elder;
    }

}
